package com.glassshop.adapter;

import java.util.List;

import com.glassshop.R;
import com.glassshop.ui.MainActivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;

/**
 * 应用程序适配器：引导页适配器
 * @author king
 * @version 1.0
 * @date 2014-12-17
 */
public class GuideAdapter extends PagerAdapter{
	
	private List<View> views;
	private Activity activity;
	
	public GuideAdapter(List<View> views, Activity activity){
		this.views = views;
		this.activity = activity;
	}
	
	@Override
	public void finishUpdate(View arg0) {
		
	}
	 

	@Override
	public int getCount() {
		if (views != null) {
			return views.size();
		}
		return 0;
	}
	
	// 销毁arg1位置的界面
		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView(views.get(arg1));
		}
	
	// 初始化arg1位置的界面
		@Override
		public Object instantiateItem(View arg0, int arg1) {
			((ViewPager) arg0).addView(views.get(arg1), 0);
			if (arg1 == views.size() - 1) {
				ImageView imageView = (ImageView) arg0.findViewById(R.id.guide_image);
				imageView.setOnClickListener(new OnClickListener()
				{
					
					@Override
					public void onClick(View arg0)
					{
						// 设置已经引导
						setGuided();
						goHome();
					}
				});
			}
			return views.get(arg1);
		}

		private void goHome() {
			// 跳转
			Intent intent = new Intent(activity, MainActivity.class);
			activity.startActivity(intent);
			activity.finish();
		}
		
		/**
		 * 
		 * 设置已经引导过了，下次启动不用再次引导
		 */
		private void setGuided() {
			SharedPreferences preferences = activity.getSharedPreferences(
					"firstIn", Context.MODE_PRIVATE);
			Editor editor = preferences.edit();
			// 存入数据
			editor.putBoolean("isFirstIn", false);
			// 提交修改
			editor.commit();
		}
		
		// 判断是否由对象生成界面
		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return (arg0 == arg1);
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
		}

}
